from flask import Blueprint, jsonify, session,render_template,request,redirect,url_for
#from ..utils.token import generate_token
from ..models.User import User
login = Blueprint('login', __name__)
from flask_jwt_extended import create_access_token, jwt_required, JWTManager, get_jwt_identity

# @login.route('/login/')
# def login_page():
#     return render_template('login.html')

# 定义生成 JWT 的函数

@login.route('/login', methods=['POST'])
def login_handle():
    data = request.json  # 获取JSON格式的请求数据
    username = data.get('username')
    password = data.get('password')

    user = User.query.filter_by(userName=username, password=password).first()
    if user is None:
        return jsonify({'status': 'fail', 'message': '用户名或密码错误'})
    else:
        # 登录成功
        userId = user.userId
        userName = user.userName
        access_token = create_access_token(identity=userName)
        session['user_id'] = userId
        session['user_name'] = userName
        session['test']="123456789"
        print("user_id",session.get('user_id'))
        print("user_name",session.get('user_name'))
        print(session.get('user_name'))
        return jsonify({'status': 'success', 'message': '登录成功', 'userName': userName,'token':access_token})
